# # Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None
#
# class Solution(object):
#     def getIntersectionNode(self, headA, headB):
#         """
#         :type head1, head1: ListNode
#         :rtype: ListNode
#         """
#
#         count1 = 0
#         count2 = 0
#         curA = headA
#         curB = headB
#         while curA != None :
#             curA = curA.next
#             count1 += 1
#         while curB != None:
#             curB = curB.next
#             count2 += 1
#
#         count = abs(count1 - count2)
#
#         if count1 >count2:
#             while count > 0:
#                 headA = headA.next
#                 count-=1
#             while headA != None:
#                 if headA == headB :
#                     return headB
#                 else:
#                     headA =headA.next
#                     headB = headB.next
#             return None
#         else:
#             while count > 0:
#                 headB = headB.next
#                 count-=1
#             while headA != None:
#                 if headA == headB :
#                     return headB
#                 else:
#                     headA =headA.next
#                     headB = headB.next
#             return None

#
# 2判断链表是否有交集，可以设置两个指针，一个指针从第一个链表开始遍历，遍历完第一个链表再遍历第二个链表，另一个指针从第二个链表开始遍历，遍历完第二个链表再遍历第一个链表，不管两个
# 链表在交集前的长度如何，如果有交集的话，两个指针肯定会同时遍历到最后的交集部分。

# Definition for singly-linked list.
class ListNode(object):
    def __init__(self, x):
        self.val = x
        self.next = None

class Solution(object):
    def getIntersectionNode(self, headA, headB):
        """
        :type head1, head1: ListNode
        :rtype: ListNode
        """
        curA = headA
        curB = headB
        if not headA or not headB:
            return None

        while curA != curB:
            curA = curA.next
            curB = curB.next
            if curA== None:
                curA = headB
            if curB == None:
                curB = headA
        return curB


l1 = ListNode(1)
l1.next = ListNode(2)
l1.next.next = ListNode(4)

l2 = ListNode(1)
l2.next = ListNode(3)
l2.next.next = l1.next


m = Solution()
s = m.getIntersectionNode(l1,l2)
print(s.val)